package com.ruoyi.document.service.impl;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.document.domain.ContractType;
import com.ruoyi.document.domain.Currency;
import com.ruoyi.document.mapper.ContractTypeMapper;
import com.ruoyi.document.mapper.CurrencyMapper;
import com.ruoyi.personnel.domain.Employee;
import com.ruoyi.personnel.mapper.EmployeeMapper;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.document.mapper.ContractMapper;
import com.ruoyi.document.domain.Contract;
import com.ruoyi.document.service.IContractService;

/**
 * 合同签约管理Service业务层处理
 *
 * @author ruoyi
 * @date 2023-03-03
 */
@Service
public class ContractServiceImpl implements IContractService {
    @Autowired
    private ContractMapper contractMapper;
    @Autowired
    private CurrencyMapper currencyMapper;
    @Autowired
    private ContractTypeMapper contractTypeMapper;
    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private  RestHighLevelClient restHighLevelClient;

    /**
     * 查询合同签约管理
     *
     * @param conId 合同签约管理主键
     * @return 合同签约管理
     */
    @Override
    public Contract selectContractByConId(Integer conId) {

        return contractMapper.selectContractByConId(conId);
    }

    /**
     * 查询合同签约管理列表
     *
     * @param contract 合同签约管理
     * @return 合同签约管理
     */
    @Override
    public List<Contract> selectContractList(Contract contract) {
        List<Contract> contracts = contractMapper.selectContractList(contract);
        BulkRequest request = new BulkRequest();
        for (Contract contract1 : contracts) {
            Currency currency = currencyMapper.selectCurrencyByCurrencyId(contract1.getCurrencyId());
            ContractType contractType = contractTypeMapper.selectContractTypeByContractId(contract1.getContractId());
            Employee employee = employeeMapper.selectEmployeeByEmpId(contract1.getEmpId());
            contract1.setContractName(contractType.getContractName());
            contract1.setCurrencyName(currency.getCurrencyName());
            contract1.setEmpName(employee.getEmpName());
            //获取时间
            Date deadline = contract1.getEffectiveTime();
            if (deadline != null) {
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                Date date = new Date();
                long a = deadline.getTime() - date.getTime();
                if (a < 0) {
                    long b = 0 - (a / 3600 / 24 / 1000);
                    System.out.println("123123：" + b);
                    contract1.setIsBlack("已逾期" + b + "天");
                } else {
                    //String format = simpleDateFormat.format(deadline);
                    //programme1.setIsBlack(format);
                }
            } else {
                contract1.setIsBlack(null);
            }

            request.add(new IndexRequest("contract").id(contract1.getConId().toString()).source(JSON.toJSONString(contract1), XContentType.JSON));
        }
        try {
            restHighLevelClient.bulk(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return contracts;
    }

    /**
     * 新增合同签约管理
     *
     * @param contract 合同签约管理
     * @return 结果
     */
    @Override
    public boolean insertContract(Contract contract) {
        // 开始时间
        Date contractTime = contract.getContractTime();
        long oldTime = contractTime.getTime();
        // 截至时间
        Date effectiveTime = contract.getEffectiveTime();
        //long newTime = effectiveTime.getTime();
        long newTime1 = System.currentTimeMillis();
        if (oldTime >= newTime1){
            oldTime = contractTime.getTime();
        }
        long newTime = 0L;

        if(effectiveTime!=null){
            newTime = effectiveTime.getTime();
        }else {
            newTime = System.currentTimeMillis();
        }
        if (oldTime < newTime) {
            //新增
            contract.setCreateTime(DateUtils.getNowDate());
            contractMapper.insertContract(contract);
            return true;
        }
        return false;
        //return contractMapper.insertContract(contract);
    }

    /**
     * 修改合同签约管理
     *
     * @param contract 合同签约管理
     * @return 结果
     */
    @Override
    public boolean updateContract(Contract contract) {
        Date effectiveTime1 = contract.getEffectiveTime();
        System.out.println("预计生效时间"+effectiveTime1);
        // 开始时间
        Date contractTime = contract.getContractTime();
        long oldTime = contractTime.getTime();
        // 截至时间
        Date effectiveTime = contract.getEffectiveTime();
        long newTime = 0L;
        long newTime1 = System.currentTimeMillis();
        if (oldTime >= newTime1){
            oldTime = contractTime.getTime();
            return false;
        }
        if(effectiveTime!=null){
            newTime = effectiveTime.getTime();
        }else {
            newTime = System.currentTimeMillis();
        }
        if (oldTime < newTime) {
            //新增
            contract.setUpdateTime(DateUtils.getNowDate());
            contractMapper.updateContract(contract);
            return true;
        }
        return false;
//        contract.setUpdateTime(DateUtils.getNowDate());
//        return contractMapper.updateContract(contract);
    }

    /**
     * 批量删除合同签约管理
     *
     * @param conIds 需要删除的合同签约管理主键
     * @return 结果
     */
    @Override
    public boolean deleteContractByConIds(Integer[] conIds) {
        String[] arr = new String[conIds.length];
        for (int i = 0; i < conIds.length; i++) {
            System.out.println("删除的id值--" + conIds[i]);
            //根据id查询出时间
            Contract vacate = contractMapper.selectContractByConId(conIds[i]);
            //数据库结束时间
            Date abEndTime = vacate.getEffectiveTime();
            if (abEndTime != null) {

                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                String abEndTime01 = simpleDateFormat.format(abEndTime);
                System.out.println("数据库结束时间" + abEndTime01);
                //当前时间
                Date date = new Date();
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
                String nowTime = formatter.format(date);
                System.out.println();
                //与当前时间做比较
                Date abEndTime02 = null;
                Date nowTime02 = null;
                try {
                    abEndTime02 = simpleDateFormat.parse(abEndTime01);
                    nowTime02 = simpleDateFormat.parse(nowTime);
                } catch (ParseException e) {
                    e.printStackTrace();
                }

                //是否超过
                boolean before = abEndTime02.before(nowTime02);
                if (before == true) {
                    //删除
                    arr[i] = "0";
                } else {
                    arr[i] = "1";
                }
            } else {
                arr[0] = "1";
            }
        }
        //数据
        String str = Arrays.toString(arr);
        if (str.contains("1")) {
            return false;
        } else {
            // vacateMapper.deleteVacateByAbIds(abIds);
            contractMapper.deleteContractByConIds(conIds);
            return true;
        }
    }

    /**
     * 删除合同签约管理信息
     *
     * @param conId 合同签约管理主键
     * @return 结果
     */
    @Override
    public int deleteContractByConId(Integer conId) {
        return contractMapper.deleteContractByConId(conId);
    }

    /**
     * 回滚
     *
     * @param array
     */
    @Override
    public void rollbackEmployee(Object[] array) {
        contractMapper.rollbackEmployee(array);
    }

    @Override
    public int updateContractById(Integer conId) {
        return contractMapper.updateContractById(conId);
    }
}
